package com.weirong.smartvault.backservice.aspect;

import com.weirong.smartvault.backservice.controller.fragment_entity.Header;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.ModelMap;
import org.springframework.validation.support.BindingAwareModelMap;

/**
 * 于2017/11/28由 KFEB4 创建 .
 */
@Aspect
@Configuration
public class Template {

    @Around(value = "execution(* com.weirong.smartvault.backservice.controller.*.*(..)) && " +
            "!execution(* com.weirong.smartvault.backservice.controller.Ajax.*(..)) &&" +
            "!execution(* com.weirong.smartvault.backservice.controller.API.*(..))" )
    public Object setHeader(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args =  pjp.getArgs();
        ModelMap model =null;
        for (Object arg :args){
            if (arg==null)
                continue;
            if (arg.getClass().equals(BindingAwareModelMap.class)) {
                model = (ModelMap) arg;
                break;
            }
        }
        if (model!=null) {
            Object rt = pjp.proceed();
            if (rt.getClass()!=String.class)
                return rt;
            String res = (String) rt;
            Header header = new Header(res);
            model.addAttribute("Header", header);
            if (!model.containsAttribute("template")) {
                if (((String) rt).startsWith("redirect"))
                    return  rt;
                model.addAttribute("template", rt);
                return "template";
            }else {
                return rt;
            }
        }else{
            return pjp.proceed();
        }
    }
}
